<template>
  <div class="coursemanage-container">
    <div class="section">
      <h3 class="favorites-title">课程资源</h3>
      <div class="folder">
        <h4 class="folder-title">资源列表</h4>
        <div class="files-container">
          <div
            class="file-item"
            v-for="(note, noteIndex) in courseResources.notes"
            :key="noteIndex"
          >
            <h4 class="note-title">{{ note.title }}</h4>
            <p class="note-content">{{ note.content }}</p>
            <p class="note-file-id">文件ID: {{ note.id }}</p>

            <button @click="openFile(note)" class="open-file-btn">打开文件</button>
            <button @click="removeFile(courseResources, noteIndex)" class="remove-btn">移除</button>
            <button @click="downloadFile(note.id)" class="download-btn">下载</button>
          </div>
          <div class="no-files" v-if="courseResources.notes.length === 0">没有文件</div>
        </div>
        <input
          type="file"
          @change="handleFileSelect($event)"
          class="file-input"
          accept=".txt,.doc,.pdf"
        />
        <button @click="uploadFile(courseResources, 1)" class="add-file-btn">添加文件</button> <!-- 假设courseid为1 -->
      </div>
    </div>

    <!-- 历年试卷库部分 -->
    <div class="section">
      <h3 class="favorites-title">历年试卷库</h3>
      <div class="folder">
        <h4 class="folder-title">试卷列表</h4>
        <div class="files-container">
          <div
            class="file-item"
            v-for="(note, noteIndex) in examPapers.notes"
            :key="noteIndex"
          >
            <h4 class="note-title">{{ note.title }}</h4>
            <p class="note-content">{{ note.content }}</p>
            <p class="note-file-id">文件ID: {{ note.id }}</p>

            <button @click="openFile(note)" class="open-file-btn">打开文件</button>
            <button @click="removeFile(examPapers, noteIndex)" class="remove-btn">移除</button>
            <button @click="downloadFile(note.id)" class="download-btn">下载</button>
          </div>
          <div class="no-files" v-if="examPapers.notes.length === 0">没有文件</div>
        </div>
        <input
          type="file"
          @change="handleFileSelect($event)"
          class="file-input"
          accept=".txt,.doc,.pdf"
        />
        <button @click="uploadFile(examPapers, 2)" class="add-file-btn">添加文件</button> <!-- 假设courseid为2 -->
      </div>
    </div>

    <!-- 习题库部分 -->
    <div class="section">
      <h3 class="favorites-title">习题库</h3>
      <div class="folder">
        <h4 class="folder-title">习题列表</h4>
        <div class="files-container">
          <div
            class="file-item"
            v-for="(note, noteIndex) in exerciseBank.notes"
            :key="noteIndex"
          >
            <h4 class="note-title">{{ note.title }}</h4>
            <p class="note-content">{{ note.content }}</p>
            <p class="note-file-id">文件ID: {{ note.id }}</p>

            <button @click="openFile(note)" class="open-file-btn">打开文件</button>
            <button @click="removeFile(exerciseBank, noteIndex)" class="remove-btn">移除</button>
            <button @click="downloadFile(note.id)" class="download-btn">下载</button>
          </div>
          <div class="no-files" v-if="exerciseBank.notes.length === 0">没有文件</div>
        </div>
        <input
          type="file"
          @change="handleFileSelect($event)"
          class="file-input"
          accept=".txt,.doc,.pdf"
        />
        <button @click="uploadFile(exerciseBank, 3)" class="add-file-btn">添加文件</button> <!-- 假设courseid为3 -->
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "CourseManage",
  data() {
    return {
      baseURL: "http://localhost:8085", // Base API URL
      courseResources: { name: '课程资源', notes: [] },
      examPapers: { name: '历年试卷库', notes: [] },
      exerciseBank: { name: '习题库', notes: [] },
      selectedFile: null, // 存储用户选择的文件
    };
  },
  methods: {
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
      }
    },

    uploadFile(folder, courseId) {
      if (!this.$store.state.token) {
        console.error('用户未登录');
        alert("用户未登录，请先登录后再操作。");
        return;
      }

      if (!this.selectedFile) {
        console.error('没有选择文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('courseid', courseId);  // 确保传递课程ID

      const token = this.$store.state.token;  // 从 Vuex 中获取 token

      axios.post(`${this.baseURL}/teacher/courseresource/addcourseware`, formData, {
        headers: { 
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`  // 在请求头中加入 Authorization
        }
      })
      .then(() => {
        const fileTitle = this.selectedFile.name;
        const fileContent = "文件名：" + this.selectedFile.name;

        folder.notes.push({
          title: fileTitle,
          content: fileContent,
          url: URL.createObjectURL(this.selectedFile),
          id: Date.now()
        });

        this.selectedFile = null; // 清空选择的文件
      })
      .catch(error => {
        if (error.response && error.response.status === 401) {
          console.error('未授权：用户未登录');
          alert("未登录，请登录后再操作。");
        } else {
          console.error('文件上传失败', error);
          alert("文件上传失败，请重试。");
        }
      });
    },

    removeFile(folder, noteIndex) {
      const note = folder.notes[noteIndex];
      const fileId = String(note.id);

      axios.delete(`${this.baseURL}/teacher/courseresource/remove`, {
        params: {
          userId: this.$store.state.status.userId,
          fileId: fileId
        }
      })
      .then(() => {
        folder.notes.splice(noteIndex, 1);
      })
      .catch(error => {
        console.error('删除文件失败', error);
        alert("删除文件失败，请重试。");
      });
    },

    downloadFile(fileId) {
      axios.get(`${this.baseURL}/courseresource/download`, {
        params: { fileId: fileId },
        responseType: 'blob'
      })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');

        let fileName = '';
        const disposition = response.headers['content-disposition'];

        if (disposition && disposition.includes('filename=')) {
          fileName = decodeURIComponent(disposition.split('filename=')[1].replace(/['"]/g, ''));
        } else {
          fileName = fileId;
        }

        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch(error => {
        console.error('文件下载失败', error);
        alert("文件下载失败，请重试。");
      });
    },

    openFile(note) {
      window.open(note.url, '_blank');
    }
  }
};
</script>

<style scoped>
.coursemanage-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section {
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.favorites-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.folder {
  margin: 10px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.folder-title {
  font-size: 18px;
  color: #333;
}

.files-container {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 5px;
}

.file-item {
  border-bottom: 1px solid #eee;
  padding: 5px 0;
}

.note-title {
  font-size: 16px;
  color: #555;
}

.note-content {
  font-size: 14px;
  color: #777;
}

.note-file-id {
  font-size: 12px;
  color: #888;
}

.open-file-btn,
.remove-btn,
.download-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.no-files {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}

.file-input {
  margin-top: 10px;
}

.add-file-btn {
  margin-top: 5px;
  background-color: #4CAF50;
}

.add-file-btn:hover {
  background-color: #388E3C;
}
</style>
